package com.pjedu.nbmallwebsitesystem.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.pjedu.nbmallcommon.common.Constants;
import com.pjedu.nbmallcommon.common.ServiceResultEnum;
import com.pjedu.nbmallcommon.utils.*;
import com.pjedu.nbmalluser.entity.MallUser;
import com.pjedu.nbmalluser.service.MallUserService;
import com.pjedu.nbmalluser.vo.MallUserVO;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Controller
public class PersonalController {

    @Resource
    private MallUserService mallUserService;

    @Resource
    private DefaultKaptcha sjKaptcha;

    @Resource
    private DefaultKaptcha phoneKaptcha;

    @GetMapping({"/login", "login.html"})
    public String loginPage() {
        return "mall/login";
    }

    //开始书写主页信息展示的逻辑,所以之前这个仅仅只用来转跳的方法,可以舍弃了
/*    @GetMapping({"/", "index.html"})
    public String mainPage() {
        return "mall/index";
    }*/

    @GetMapping({"/register", "register.html"})
    public String registerPage() {
        return "mall/register";
    }

    @GetMapping("/personal/safe")
    public String addressesPage() {
        return "mall/personal/safe";
    }

    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestParam("loginName") String loginName,
                        @RequestParam("password") String password,
                        @RequestParam("validateCode") String validateCode,
                        HttpSession httpSession) throws Exception {
        //非空校验
        if (StringUtils.isEmpty(loginName)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_NAME_NULL.getResult());
        }
        if (StringUtils.isEmpty(password)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_PASSWORD_NULL.getResult());
        }
        if (StringUtils.isEmpty(validateCode)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_VERIFY_CODE_NULL.getResult());
        }
        //验证码的校验
        if (!httpSession.getAttribute("verifyCode").equals(validateCode)){
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_VERIFY_CODE_ERROR.getResult());
        }
        //进行登录
        MallUser user = mallUserService.login(loginName, MD5Util.MD5Encode(password, "UTF-8"));
        if (user == null) {
            //登录失败
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_ERROR.getResult());
        }
        //昵称太长影响页面展示
        if (user.getNickName() != null && user.getNickName().length() > 7) {
            String tempNickName = user.getNickName().substring(0, 7) + "..";
            user.setNickName(tempNickName);
        }
        //登录成功,把user对象转成对应的vo对象
        MallUserVO mallUserVO = new MallUserVO();
        BeanUtil.copyProperties(user, mallUserVO);
        //把vo对象绑定到session中,可以从中得到购物车中的数量
        httpSession.setAttribute(Constants.MALL_USER_SESSION_KEY, mallUserVO);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestParam("loginName") String loginName,
                           @RequestParam("password") String password,
                           @RequestParam("validateCode") String validateCode,
                           HttpSession httpSession) {
        if (StringUtils.isEmpty(loginName)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_NAME_NULL.getResult());
        }
        if (StringUtils.isEmpty(password)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_PASSWORD_NULL.getResult());
        }
        if (StringUtils.isEmpty(validateCode)) {
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_VERIFY_CODE_NULL.getResult());
        }
        //验证码的校验
        if (!httpSession.getAttribute(Constants.KAPTCHA_SESSION_KEY).equals(validateCode)){
            return ResultGenerator.genFailResult(ServiceResultEnum.LOGIN_VERIFY_CODE_ERROR.getResult());
        }
        String registerResult = mallUserService.register(loginName, password);
        //注册成功
        if (ServiceResultEnum.SUCCESS.getResult().equals(registerResult)) {
            return ResultGenerator.genSuccessResult();
        }
        //注册失败
        return ResultGenerator.genFailResult(registerResult);
    }
    //登录验证码-随机数
    @GetMapping("/captcha/captchaImage")
    public void getKaptcha(HttpSession httpSession, HttpServletResponse httpServletResponse) throws IOException {
        // 1. 生成验证文字内容
        String verifyCode = sjKaptcha.createText();
        // 1.1 把验证码的内容放到session里面【服务器存储】
        httpSession.setAttribute("verifyCode", verifyCode);
        // 1.2 把验证码生成的文字内容构建成一张图片
        BufferedImage image = sjKaptcha.createImage(verifyCode);
        // 2. 返回图片内容到页面
        ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", imgOutputStream);
        byte[] byteImage = imgOutputStream.toByteArray();
        // 2.1 返回的响应内容中就是图片， 同时设置 响应头， 浏览器根据类型去识别
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        httpServletResponse.getOutputStream().write(byteImage);
        httpServletResponse.getOutputStream().flush();
        httpServletResponse.getOutputStream().close();
        System.out.println("获取一个验证码");
    }
    //注册验证码--手机匹配
    @PostMapping("/captcha/captchaPhone")
    public void getKaptchaPhone(HttpSession session,HttpServletRequest request,HttpServletResponse response){
        ServletOutputStream out = null;
        try {
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");
            String code = phoneKaptcha.createText();
            // TODO 我们没接短信平台，所以直接后台打印一下吧
            String phoneNumber = request.getParameter("phoneNumber");
            System.out.println(phoneNumber + "此次注册所用的短信验证码为：" + code);
            // 放到session 用于下次校验
            session.setAttribute(Constants.KAPTCHA_SESSION_KEY, code);
            // 返回给客户端提示
            Result result = ResultGenerator.genSuccessResult("短信验证码已发送");
            try {
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().print(new ObjectMapper().writeValueAsString(result));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession httpSession) {
        httpSession.removeAttribute(Constants.MALL_USER_SESSION_KEY);
        return "redirect:/";
    }

    @GetMapping("/personal/index")
    public String personalPage(HttpServletRequest request,
                               @RequestParam(Constants.LOGIN_USER_USER_ID) Long loginUserId) {
        request.setAttribute("path", "personal");
        request.setAttribute("mallUser", mallUserService.getUserDetailById(loginUserId));
        return "mall/personal/index";
    }

    @PostMapping("/personal/updateInfo")
    @ResponseBody
    public Result updateInfo(@RequestBody MallUser mallUser, HttpSession httpSession,
                             @RequestParam(Constants.LOGIN_USER_USER_ID) Long loginUserId) {
        MallUser userFromDB = mallUserService.getUserDetailById(loginUserId);
        userFromDB.setNickName(Utils.cleanString(mallUser.getNickName()));
        userFromDB.setAddress(Utils.cleanString(mallUser.getAddress()));
        userFromDB.setIntroduceSign(Utils.cleanString(mallUser.getIntroduceSign()));
        mallUserService.updateUserInfo(userFromDB);
        MallUserVO mallUserVO = new MallUserVO();
        BeanUtil.copyProperties(userFromDB, mallUserVO);
        httpSession.setAttribute(Constants.MALL_USER_SESSION_KEY, mallUserVO);

        //返回成功
        Result result = ResultGenerator.genSuccessResult();
        return result;
    }

    @PostMapping("/personal/updatePassword")
    @ResponseBody
    public Result updatePassword(String oldPassword, String newPassword,
                                 @RequestParam(Constants.LOGIN_USER_USER_ID) Long loginUserId) {
        MallUser userFromDB = mallUserService.getUserDetailById(loginUserId);
        if (userFromDB.getPasswordMd5().equals(MD5Util.MD5Encode(oldPassword, "UTF-8"))) {
            userFromDB.setPasswordMd5(MD5Util.MD5Encode(newPassword, "UTF-8"));
            mallUserService.updateUserInfo(userFromDB);
            //返回成功
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("密码错误");
        }
    }
}
